define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            //查看推广码
            $(document).on('click', 'a[data-class="promotion_qr_data"]', function(){
                var url = 'api/wanlshop/common/mpQrcode?data='+$(this).data('promotion_qr_data');
                layer.open({
                    type: 1, // 页面层
                    area: ['300px', '300px'], // 弹窗大小自适应
                    title: false, // 不显示标题栏
                    closeBtn: 1, // 显示关闭按钮
                    shade: 0.5, // 遮罩层透明度
                    content: '<img src="/'+url+'" width="300" hide="300">'
                });
            });
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'item/item/index' + location.search,
                    add_url: 'item/item/add',
                    // edit_url: 'item/item/edit',
                    reuse_url: 'item/item/reuse',
                    del_url: 'item/item/del',
                    multi_url: 'item/item/multi',
                    resubmit_url: 'item/item/resubmit',
                    import_url: 'item/item/import',
                    table: 'item',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            $(document).on("click", ".goods-shop-type-item", function () {
                $(".active-type").removeClass('active-type');
                $(this).addClass('active-type');
                window.location =  $(this).data('url');
            });

            $(document).on("click", ".btn-resubmit", function () {
                var ids = Table.api.selectedids(table);
                Fast.api.open("item/item/resubmit/ids/" + ids, __('批量铺设'), {
                    area: ['90%', '90%']
                });
            });

            $(document).on("click", ".btn-batch", function () {
                var ids = Table.api.selectedids(table);
                Fast.api.open("item/item/batch/ids/" + ids, __('批量下架'), {
                    area: ['800px', '500px']
                });
            });
            
            $(document).on('click', '.btn-batchprice', function() {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    Layer.msg("请选择要修改的卡项");
                    return;
                }

                selectShopModal(ids);
            });

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                Search: true,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), operate: false },
                        // {field: 'shop_id', title: __('Shop_id')},
                        //     {field: 'code', title: __('Code'), operate: 'LIKE'},
                        { field: 'name', title: __('Name'), operate: false },
                        {field: 'promotion_qr_data', title: __('推广码'), align: 'center', formatter:function(value, row, index){
                            return '<a href="javascript:void(0)" class="btn btn-xs btn-success" data-class="promotion_qr_data" data-promotion_qr_data="'+value+'">查看</a>';
                        }},
                        { field: 'item.name', title: __('Name'), operate: 'LIKE',visible:false },
                        { field: 'type', title: __('Type'), searchList: { "1": __('Type 1'), "2": __('Type 2'), "3": __('Type 3'), "4": __('Type 4'), "5": __('Type 5') }, formatter: Table.api.formatter.normal },
                        // { field: 'flag.name', title: __('Category_id') },


                        // {field: 'consumption', title: __('Consumption'), searchList: {"1":__('Consumption 1'),"2":__('Consumption 2'),"3":__('Consumption 3'),"4":__('Consumption 4')}, formatter: Table.api.formatter.normal},
                        { field: 'price', title: __('Price'), operate: false },
                        {field: 'vip_price',title: __('会员价'),operate: false},
                        {field: 'on_sale_shop',title: __('在售门店'),operate: false,
                            formatter: function(value, row, index) {
                                // 生成带点击事件的链接，传递商品ID
                                return '<a href="javascript:;" class="btn btn-xs btn-primary js-view-shops" data-id="' + row.id + '">' + value + ' 家店铺</a>';
                            }
                        },
                        //{field: 'specs', title: __('Specs'), searchList: {"1":__('Specs 1')}, formatter: Table.api.formatter.normal},
                        //{field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        //                 {field: 'gift', title: __('Gift'), operate:'BETWEEN'},
                        //{field: 'spent', title: __('Spent')},
                        //              {field: 'total', title: __('Total')},
                        { field: 'validity', title: __('Validity'), operate: false, searchList: { "0": __('Validity 0'), "1": __('Validity 1'),"2": __('Validity 2'), "3": __('Validity 3') }, formatter: Table.api.formatter.normal },
                        // {field: 'validitytime', title: __('Validitytime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'shop_ids', title: __('Shop_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'stock', title: __('Stock'), searchList: {"0":__('Stock 0'),"2":__('Stock 2'),"3":__('Stock 3')}, formatter: Table.api.formatter.normal},
                        { field: 'activity', title: __('Activity'), operate: false, searchList: { "0": __('Activity 0'), "1": __('Activity 1') }, formatter: Table.api.formatter.normal },
                        //  {field: 'distribution', title: __('Distribution'), searchList: {"0":__('Distribution 0'),"1":__('Distribution 1')}, formatter: Table.api.formatter.normal},
                        //   {field: 'flag', title: __('Flag'), searchList: {"type":__('Flag type'),"name":__('Flag name'),"rec":__('Flag rec')}, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        //  {field: 'activity_type', title: __('Activity_type'), searchList: {"goods":__('Activity_type goods'),"groups":__('Activity_type groups'),"seckill":__('Activity_type seckill'),"bargain":__('Activity_type bargain')}, formatter: Table.api.formatter.normal},
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        //{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        { field: 'status', title: __('Status'), searchList: { "normal": __('Normal'), "hidden": __('Hidden') }, formatter: Table.api.formatter.status },
                        // { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons :[
                                {
                                    name: 'resubmit',
                                    text: '铺设',
                                    title: '铺设',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: "item/item/resubmit",
                                    hidden:function(row){
                                        if(row.show_copy == 0){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                },
                                {
                                    name: 'reuse',
                                    text: '复制',
                                    title: '复制',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    url: "item/item/reuse",
                                },
                            ],
                            callback: function (data) {
                                table.bootstrapTable('refresh', {});
                                return false;
                            },
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });
    
            $(document).on('click', '.js-view-shops', function() {
                var goodsId = $(this).data('id');
                loadShopList(goodsId, 1); // 加载第一页数据
            });

            // 加载店铺列表数据
            function loadShopList(goodsId, page) {
                // 显示加载状态
                $('.loading').removeClass('hide');
                $('.table-responsive, #sublistEmpty').addClass('hide');
                
                // 发送AJAX请求
                $.ajax({
                    url: 'item/item/onsaleshops', // 后端接口URL
                    method: 'GET',
                    data: {
                        id: goodsId,
                        page: page,
                        limit: 10 // 每页10条数据
                    },
                    success: function(res) {
                        if (res.code === 0) {
                            renderShopList(res);
                            renderPagination(res, goodsId);
                            updatePaginationInfo(res);
                            $('#sublistModal').modal('show');
                        } else {
                            Layer.msg(res.msg || '获取数据失败', {icon: 2});
                        }
                    },
                    error: function() {
                        Layer.msg('网络请求失败', {icon: 2});
                    },
                    complete: function() {
                        $('.loading').addClass('hide');
                    }
                });
            }

            // 渲染店铺列表
            function renderShopList(res) {
                var tbody = $('#sublistBody');
                tbody.empty();
                
                if (res.data && res.data.length > 0) {
                    res.data.forEach(function(item) {
                        var tr = $('<tr>');
                        tr.append('<td>' + item.id + '</td>');
                        tr.append('<td>' + item.shopname + '</td>');
                        tr.append('<td>' + item.person + '</td>');
                        tr.append('<td>' + item.telephone + '</td>');
                        tr.append('<td>' + item.adds + '</td>');
                        tbody.append(tr);
                    });
                    $('.table-responsive').removeClass('hide');
                    $('#sublistEmpty').addClass('hide');
                } else {
                    $('.table-responsive').addClass('hide');
                    $('#sublistEmpty').removeClass('hide');
                }
            }

            // 更新分页信息显示
            function updatePaginationInfo(res) {
                const start = ((res.current_page - 1) * res.per_page) + 1;
                const end = Math.min(res.current_page * res.per_page, res.total);
                
                const infoText = `
                    <span class="text-sm text-gray-700">
                        显示 <span class="font-medium">${start}</span> 到 <span class="font-medium">${end}</span> 条，
                        共 <span class="font-medium">${res.total}</span> 条记录
                    </span>
                `;
                
                $('#paginationInfo').html(infoText);
            }

            // 渲染分页控件
            function renderPagination(res, goodsId) {
                const pagination = $('#sublistPagination');
                pagination.empty();
                
                const currentPage = res.current_page;
                const lastPage = res.last_page;
                const baseUrl = 'javascript:void(0)';
                
                // 如果只有一页或没有数据，不显示分页控件
                if (lastPage <= 1 || res.total === 0) {
                    $('.pagination-container').addClass('hidden');
                    return;
                } else {
                    $('.pagination-container').removeClass('hidden');
                }
                
                // 添加上一页按钮
                const prevDisabled = currentPage === 1;
                const prevButton = `
                    <li class="page-item ${prevDisabled ? 'opacity-50 cursor-not-allowed' : ''}">
                        <a class="page-link flex items-center justify-center w-10 h-10 rounded-lg border border-gray-300 bg-white text-gray-500 transition-all duration-200" 
                           href="${baseUrl}" 
                           data-page="${currentPage - 1}" 
                           data-id="${goodsId}"
                           ${prevDisabled ? 'onclick="return false;" disabled' : ''}>
                            <i class="fa fa-chevron-left text-xs"></i>
                        </a>
                    </li>
                `;
                pagination.append(prevButton);
                
                // 显示第一页（如果当前页不是第一页且距离第一页超过2页）
                if (currentPage > 3) {
                    appendPageButton(1, goodsId, currentPage);
                    
                    // 添加省略号
                    if (currentPage > 4) {
                        pagination.append(`
                            <li class="page-item disabled">
                                <span class="page-link flex items-center justify-center w-10 h-10 text-gray-400">...</span>
                            </li>
                        `);
                    }
                }
                
                // 显示当前页附近的页码
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(lastPage, currentPage + 2);
                
                for (let i = startPage; i <= endPage; i++) {
                    appendPageButton(i, goodsId, currentPage);
                }
                
                // 显示最后一页（如果当前页不是最后一页且距离最后一页超过2页）
                if (currentPage < lastPage - 2) {
                    // 添加省略号
                    if (currentPage < lastPage - 3) {
                        pagination.append(`
                            <li class="page-item disabled">
                                <span class="page-link flex items-center justify-center w-10 h-10 text-gray-400">...</span>
                            </li>
                        `);
                    }
                    
                    appendPageButton(lastPage, goodsId, currentPage);
                }
                
                // 添加下一页按钮
                const nextDisabled = currentPage === lastPage;
                const nextButton = `
                    <li class="page-item ${nextDisabled ? 'opacity-50 cursor-not-allowed' : ''}">
                        <a class="page-link flex items-center justify-center w-10 h-10 rounded-lg border border-gray-300 bg-white text-gray-500 transition-all duration-200" 
                           href="${baseUrl}" 
                           data-page="${currentPage + 1}" 
                           data-id="${goodsId}"
                           ${nextDisabled ? 'onclick="return false;" disabled' : ''}>
                            <i class="fa fa-chevron-right text-xs"></i>
                        </a>
                    </li>
                `;
                pagination.append(nextButton);
                
                // 绑定分页按钮点击事件
                $('.page-link:not([disabled])').click(function() {
                    const page = $(this).data('page');
                    const id = $(this).data('id');
                    loadShopList(id, page);
                });
            }

            // 辅助函数：添加页码按钮
            function appendPageButton(pageNum, goodsId, currentPage) {
                const isActive = pageNum === currentPage;
                const pagination = $('#sublistPagination');
                
                const buttonClass = isActive 
                    ? 'bg-primary text-white border-primary shadow-md curr-item hover:bg-primary/90' 
                    : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50';
                
                pagination.append(`
                    <li class="page-item">
                        <a class="page-link flex items-center justify-center w-10 h-10 rounded-lg ${buttonClass} transition-all duration-200" 
                           href="javascript:void(0)" 
                           data-page="${pageNum}" 
                           data-id="${goodsId}"
                           ${isActive ? 'onclick="return false;" disabled' : ''}>
                            ${pageNum}
                        </a>
                    </li>
                `);
            }
            

            //批量改价相关事件
            // 店铺选择模态框
            function selectShopModal(goodsIds) {
                // 使用FastAdmin的modal方法弹出店铺选择框
                Fast.api.open("item/item/shoplist", __('选择店铺'), 
                {
                    area: ['90%', '90%'],
                    callback: function(data) {
                        if (data && data.shop_ids && data.shop_ids.length > 0) {
                            setPriceModal(goodsIds, data.shop_ids);
                        }
                    }
                }
                );
            }

            // 价格设置模态框
            function setPriceModal(goodsIds, shopIds) {
                // 创建价格设置表单
                var formHtml = '<div class="form-group">' +
                                '<label for="price" class="control-label col-xs-12 col-sm-3">价格</label>' +
                                '<div class="col-xs-12 col-sm-9">' +
                                '<input type="number" class="form-control" id="goodsprice" name="goodsprice" min="0" step="0.01" required>' +
                                '<p class="help-block">请输入新的卡项价格</p>' +
                                '</div>' +
                                '</div>'+ 
                                '<div class="form-group">' +
                                '<label for="price" class="control-label col-xs-12 col-sm-3">名称</label>' +
                                '<div class="col-xs-12 col-sm-9">' +
                                '<input type="text" class="form-control" id="goodstitle" name="goodstitle" required>' +
                                '<p class="help-block">请输入新的卡项名称</p>' +
                                '</div>' +
                                '</div>';
                
                // 弹出价格设置模态框，并保存其索引
                var modalIndex = Layer.open({
                    title: '设置卡项信息',
                    content: formHtml,
                    btn: ['确定', '取消'],
                    area: ['40%', '30%'],
                    yes: function(index, layero) {
                        var price = $('#goodsprice').val();
                        var title = $('#goodstitle').val();
                        if (!price) {
                            // 显示错误提示，但不关闭价格设置模态框
                            layer.msg('价格不能为空', {
                                icon: 2, // 使用错误图标
                                time: 2000 // 2秒后自动关闭提示
                                // 不需要end回调，因为我们不想关闭价格设置模态框
                            });
                            return false; // 阻止关闭价格设置模态框
                        }
                        
                        // 显示加载状态
                        var loadingIndex = layer.load(1, {
                            shade: [0.1,'#fff'] // 0.1透明度的白色背景
                        });

                        // 发送请求到后台处理
                        updateGoodsPrice(goodsIds, shopIds, price, title, function(success, message) {
                            // 无论成功或失败，都关闭加载状态
                            layer.close(loadingIndex);
                            
                            if (success) {
                                layer.msg(message || '价格更新成功', {icon: 1, time: 1500});
                                Layer.close(modalIndex); // 关闭价格设置模态框
                            } else {
                                layer.msg(message || '价格更新失败', {icon: 2, time: 2000});
                            }
                        });
                        $("a.btn-refresh").trigger("click");     
                        return false; // 阻止默认关闭行为，等待回调处理
                    }
                });
            }

            function updateGoodsPrice(goodsIds, shopIds, price,title, callback) {
                Fast.api.ajax({
                    url: 'item/item/batchUpdatePrice',
                    data: {
                        goods_ids: goodsIds,
                        shop_ids: shopIds,
                        price: price,
                        title: title
                    }
                }, function(data, ret) {
                    if (callback) callback(true, ret.msg);
                    return false;
                }, function(data, ret) {
                    if (callback) callback(false, ret.msg);
                    return false;
                });
            }

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        shoplist: function () {
            var goods_id = Config.goods_id;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'item/item/shoplist' + location.search,
                    table: 'wanlshop_shop',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:false,
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });

            $("button[type='submit']").css("background-color","red");
            $("button[type='submit']").css("border-color","red");

            //保存设置
            $(document).on("click", ".choose-shop", function () {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    layer.msg("请选择要设置的店铺！");
                }

                Fast.api.close({shop_ids: ids});
            });
            
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'item/item/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'name', title: __('Name'), align: 'left' },
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'item/item/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'item/item/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
            $("#recharge").hide();
            $("#shop").hide();
            $("#back").hide();
            $("#gift").hide();
            $("#buyshow").hide();
            $("#sendshow").hide();

            $(document).ready(function () {
                $('input[name="row[validity]"]').change(function () {
                    var validity = $('input[name="row[validity]"]:checked').val();
                    if (validity == 0) {
                        $('input[name="row[day]"]').val('')
                        $('input[name="row[use_day]"]').val('')
                        $('input[name="row[time]"]').val('')
                    }
                    if (validity == 1) {
                        $('input[name="row[day]"]').val('')
                        $('input[name="row[user_day]"]').val('')
                    }
                    if (validity == 2) {
                        $('input[name="row[time]"]').val('')
                        $('input[name="row[user_day]"]').val('')
                    }
                    if (validity == 3) {
                        $('input[name="row[time]"]').val('')
                        $('input[name="row[day]"]').val('')
                    }
                });
                $('#c-type').change(function () {
                    var selectedValue = $(this).val(); // 获取选中的值
                    // 根据选中的值进行相应的操作
                    if (selectedValue) {
                        // 执行相应的操作
                        // 例如，根据选中的值显示或隐藏其他元素
                        if (selectedValue == 1 || selectedValue == 2 || selectedValue == 3) {
                            $('#card').show();
                            $("#recharge").hide();
                            $('#consu').show();
                            $("#gift").hide();
                            $("#buycard").show();
                            $('#buycardsend').show();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                        if (selectedValue == 4) {
                            $('#card').hide();
                            $("#recharge").show();
                            $('#consu').show();
                            $("#gift").show();
                            $("#buycard").hide();
                            $('#buycardsend').hide();

                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                        if (selectedValue == 5) {
                            $('#consu').hide();
                            $("#gift").hide();
                            $("#buycard").hide();
                            $('#buycardsend').show();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                    }
                });
            });
            $(document).ready(function () {
                $('input[name="row[stock]"]').change(function () {
                    var id = $('input[name="row[stock]"]:checked').val();
                    if (id == 2 || id == 3) {
                        $("#shop").show();
                    } else {
                        $("#shop").hide();
                    }
                })
            });
            $(document).ready(function () {
                $('input[name="row[specs]"]').change(function () {
                    var id = $('input[name="row[specs]"]:checked').val();
                    if (id == 2) {
                        $("#back").show();
                    } else {
                        $("#back").hide();
                    }
                })
            });
            $("#addGoods").click(function () {

                var type = $("#c-type").val();
                if (type != 3) {
                    $('.all-num-box').hide()
                }
                layer.open({
                    type: 2,
                    title: '添加商品',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: 'add_goods?type=' + type,
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        var form = layer.getChildFrame("input[name*='row']").serialize();
                        console.log(form)
                        Fast.api.ajax({
                            type: 'post',
                            url: 'item/item/goods_data',
                            dataType: 'json',
                            data: { form: form },
                            cache: false
                        }, function (ret) {
                            $('.all-num-box').val('')
                            $("#buyshow").show();
                            var buyHead = '<tr>\n' +
                                '                                        <th scope="col">已选服务（' + ret.row.goods.length + ')</th>\n' +
                                '                                        <th scope="col">规格</th>\n' +
                                '                                        <th scope="col">售价</th>\n' +
                                '                                        <th scope="col">可用次数</th>\n' +
                                // '                                        <th scope="col">操作</th>\n' +
                                '                                </tr>'

                            $("#buyHead").html(buyHead);
                            var item = '';
                            $.each(ret.row.goods, function (k, v) {
                                item += "<tr id='del_" + v['sku_id'] + "'>" +
                                    "<td class='col-xs-3' ><input type='hidden' name='row[goods][" + k + "][title]' value='" + v['title'] + "'><input type='hidden' name='row[goods][" + k + "][sku_id]' value='" + v['sku_id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][goods_id]' value='" + v['goods_id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][image]' value='" + v['image'] + "'> ";
                                item += v['title'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][difference]' value='" + v['difference'] + "'>";
                                item += v['difference'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][price]' value='" + v['price'] + "'>";
                                item += v['price'];
                                item += '</td><td class="col-xs-3"><input type="text" class="ipt-num" name="row[goods][' + k + '][nums]" value="' + v["nums"] + '" readonly></td>' +
                                    '<td class="col-xs-3">';

                                item += '</td></tr>';
                            })
                            $('#buytable').html(item)

                        });
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：
                        layer.close(index);

                    },
                })
            });
            $("#addSendGoods").click(function () {
                var type = $("#c-type").val();
                layer.open({
                    type: 2,
                    title: '赠送服务',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: 'send_goods?type=' + type,
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        var form = layer.getChildFrame("input[name*='row']").serialize();
                        console.log(form)
                        Fast.api.ajax({
                            type: 'post',
                            url: 'item/item/goods_data',
                            dataType: 'json',
                            data: { form: form },
                            cache: false
                        }, function (ret) {
                            $("#sendshow").show();
                            var buyHead = '<tr>\n' +
                                '                                        <th scope="col">已选服务（' + ret.row.send_goods.length + ')</th>\n' +
                                '                                        <th scope="col">规格</th>\n' +
                                '                                        <th scope="col">售价</th>\n' +
                                '                                        <th scope="col">可用次数</th>\n' +
                                // '                                        <th scope="col">操作</th>\n' +
                                '                                </tr>'

                            $("#sendHead").html(buyHead);
                            var item = '';
                            $.each(ret.row.send_goods, function (k, v) {
                                item += "<tr id='del_" + v['sku_id'] + "'>" +
                                    "<td class='col-xs-3' ><input type='hidden' name='row[send_goods][" + k + "][title]' value='" + v['title'] + "'><input type='hidden' name='row[send_goods][" + k + "][sku_id]' value='" + v['sku_id'] + "'> " +
                                    "<input type='hidden' name='row[send_goods][" + k + "][goods_id]' value='" + v['goods_id'] + "'> " +
                                    "<input type='hidden' name='row[send_goods][" + k + "][image]' value='" + v['image'] + "'> ";
                                item += v['title'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[send_goods][" + k + "][difference]' value='" + v['difference'] + "'>";
                                item += v['difference'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[send_goods][" + k + "][price]' value='" + v['price'] + "'>";
                                item += v['price'];
                                item += '</td><td class="col-xs-3"><input type="text" name="row[send_goods][' + k + '][nums]" value="' + v["nums"] + '" readonly></td>' +
                                    '<td class="col-xs-3">';

                                item += '</td></tr>';
                            })
                            $('#sendtable').html(item)

                        });
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：
                        layer.close(index);

                    },
                })
            });
        },
        edit: function () {
            Controller.api.bindevent();
            $("#recharge").hide();
            $("#shop").hide();
            $("#back").hide();
            $(document).ready(function () {
                var stock = $('#stock').html();
                if (stock == 2 || stock == 3) {
                    $("#shop").show();
                }
                var type = $('#type').html();
                if (type == 1 || type == 2) {
                    $('#card').show();
                    $("#recharge").hide();
                    $('#consu').show();
                }
                if (type == 3 || type == 4) {
                    $('#card').hide();
                    $("#recharge").show();
                    $('#consu').show();
                }
                if (type == 5) {
                    $('#consu').hide();
                }
                var specs = $('#specs').html();
                if (specs == 2) {
                    $("#back").show();
                }
                $('input[name="row[validity]"]').change(function () {
                    var validity = $('input[name="row[validity]"]:checked').val();
                    if (validity == 0) {
                        $('input[name="row[day]"]').val('')
                        $('input[name="row[use_day]"]').val('')
                        $('input[name="row[time]"]').val('')
                    }
                    if (validity == 1) {
                        $('input[name="row[day]"]').val('')
                        $('input[name="row[use_day]"]').val('')
                    }
                    if (validity == 2) {
                        $('input[name="row[time]"]').val('')
                        $('input[name="row[use_day]"]').val('')
                    }
                    if (validity == 3) {
                        $('input[name="row[time]"]').val('')
                        $('input[name="row[day]"]').val('')
                    }
                });
                $('#c-type').change(function () {
                    var selectedValue = $(this).val(); // 获取选中的值
                    // 根据选中的值进行相应的操作
                    if (selectedValue) {
                        // 执行相应的操作
                        // 例如，根据选中的值显示或隐藏其他元素
                        if (selectedValue == 1 || selectedValue == 2 || selectedValue == 3) {
                            $('#card').show();
                            $("#recharge").hide();
                            $('#consu').show();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                        if (selectedValue == 4) {
                            $('#card').hide();
                            $("#recharge").show();
                            $('#consu').show();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                        if (selectedValue == 5) {
                            $('#consu').hide();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                    }
                });

                $('input[name="row[stock]"]').change(function () {
                    var id = $('input[name="row[stock]"]:checked').val();
                    if (id == 2 || id == 3) {
                        $("#shop").show();
                    } else {
                        $("#shop").hide();
                    }
                })

                $('input[name="row[specs]"]').change(function () {
                    var id = $('input[name="row[specs]"]:checked').val();
                    if (id == 2) {
                        $("#back").show();
                    } else {
                        $("#back").hide();
                    }
                })
                $("#addGoods").click(function () {
                    layer.open({
                        type: 2,
                        title: '添加商品',
                        shadeClose: true,
                        shade: 0.8,
                        area: ['100%', '100%'],
                        content: 'add_goods',
                        btn: ['确定', '取消'],
                        yes: function (index, layero) {
                            var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            var data = iframeWin.getData();
                            console.log(data);
                            $("#goods").val(data);
                            layer.close(index);

                        },
                    })
                });
            });
        },
        reuse: function () {
            Controller.api.bindevent();
            $("#recharge").hide();
            $("#shop").hide();
            $("#back").hide();
            $(document).ready(function () {
                var stock = $('#stock').html();
                if (stock == 2 || stock == 3) {
                    $("#shop").show();
                }
                var type = $('#type').html();
                if (type == 1 || type == 2) {
                    $('#card').show();
                    $("#recharge").hide();
                    $('#consu').show();
                }
                if (type == 3 || type == 4) {
                    $('#card').hide();
                    $("#recharge").show();
                    $('#consu').show();
                }
                if (type == 5) {
                    $('#consu').hide();
                }
                var specs = $('#specs').html();
                if (specs == 2) {
                    $("#back").show();
                }
                $('input[name="row[validity]"]').change(function () {
                    var validity = $('input[name="row[validity]"]:checked').val();
                    if (validity == 0) {
                        $('input[name="row[day]"]').val('')
                        $('input[name="row[use_day]"]').val('')
                        $('input[name="row[time]"]').val('')
                    }
                    if (validity == 1) {
                        $('input[name="row[day]"]').val('')
                        $('input[name="row[use_day]"]').val('')
                    }
                    if (validity == 2) {
                        $('input[name="row[time]"]').val('')
                        $('input[name="row[use_day]"]').val('')
                    }
                    if (validity == 3) {
                        $('input[name="row[time]"]').val('')
                        $('input[name="row[day]"]').val('')
                    }
                });
                $('#c-type').change(function () {
                    var selectedValue = $(this).val(); // 获取选中的值
                    // 根据选中的值进行相应的操作
                    if (selectedValue) {
                        // 执行相应的操作
                        // 例如，根据选中的值显示或隐藏其他元素
                        if (selectedValue == 1 || selectedValue == 2 || selectedValue == 3) {
                            $('#card').show();
                            $("#recharge").hide();
                            $('#consu').show();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                        if (selectedValue == 4) {
                            $('#card').hide();
                            $("#recharge").show();
                            $('#consu').show();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                        if (selectedValue == 5) {
                            $('#consu').hide();
                            $('input[name="row[consumption]"]').removeAttr('checked');
                        }
                    }
                });
            });
            $(document).ready(function () {
                $('input[name="row[stock]"]').change(function () {
                    var id = $('input[name="row[stock]"]:checked').val();
                    if (id == 2 || id == 3) {
                        $("#shop").show();
                    } else {
                        $("#shop").hide();
                    }
                })
            });
            $(document).ready(function () {
                $('input[name="row[specs]"]').change(function () {
                    var id = $('input[name="row[specs]"]:checked').val();
                    if (id == 2) {
                        $("#back").show();
                    } else {
                        $("#back").hide();
                    }
                })
            });
            $("#addGoods").click(function () {
                layer.open({
                    type: 2,
                    title: '添加商品',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: 'add_goods',
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                        var data = iframeWin.getData();
                        console.log(data);
                        $("#goods").val(data);
                        layer.close(index);

                    },
                })
            });
        },
        add_goods: function () {
            $("#showTable").hide()
            Controller.api.bindevent();

            $(document).on("click", "#c-goods", function () {
                //后续操作
                
                var name = $("#c-name").val();
                var type = $("#type").html();
                Fast.api.ajax({
                    url: 'item/item/get_goods',
                    dataType: 'json',
                    data: { name: name },
                    cache: false
                }, function (ret) {
                    $('.all-num').val('')
                    if (ret.length > 0) {
                        $("#showTable").show()
                        var head = '<tr>\n' +
                            '                                        <th scope="col">已选服务（' + ret.length + '）</th>\n' +
                            '                                        <th scope="col">规格</th>\n' +
                            '                                        <th scope="col">售价</th>\n' +
                            '                                        <th scope="col">可用次数</th>\n' +
                            // '                                        <th scope="col">操作</th>\n' +
                            '                                </tr>'
                        $("#head").html(head);
                        var item = '';
                        if (type == 2) {
                            $.each(ret, function (k, v) {

                                item += "<tr id='del_" + v['sku']['id'] + "'>" +
                                    "<td class='col-xs-3' ><input type='hidden' name='row[goods][" + k + "][title]' value='" + v['goods']['title'] + "'><input type='hidden' name='row[goods][" + k + "][sku_id]' value='" + v['sku']['id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][goods_id]' value='" + v['goods']['id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][image]' value='" + v['goods']['image'] + "'> ";
                                item += v['goods']['title'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][difference]' value='" + v['sku']['difference'] + "'>";
                                item += v['sku']['difference'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][price]' value='" + v['sku']['price'] + "'>";
                                item += v['sku']['price'];
                                item += '</td><td class="col-xs-3"><input type="text"  name="row[goods][' + k + '][nums]" value="无限次" readonly></td>' +
                                    '<td class="col-xs-3">';

                                item += '</td></tr>';
                            })
                        } else if (type == 3) {
                            $.each(ret, function (k, v) {

                                item += "<tr id='del_" + v['sku']['id'] + "'>" +
                                    "<td class='col-xs-3' ><input type='hidden' name='row[goods][" + k + "][title]' value='" + v['goods']['title'] + "'><input type='hidden' name='row[goods][" + k + "][sku_id]' value='" + v['sku']['id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][goods_id]' value='" + v['goods']['id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][image]' value='" + v['goods']['image'] + "'> ";
                                item += v['goods']['title'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][difference]' value='" + v['sku']['difference'] + "'>";
                                item += v['sku']['difference'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][price]' value='" + v['sku']['price'] + "'>";
                                item += v['sku']['price'];
                                item += '</td><td class="col-xs-3"><input type="number" class="ipt-num" name="row[goods][' + k + '][nums]" value="" readonly></td>' +
                                    '<td class="col-xs-3">';
                                // item+=v['mobile'];
                                // item+='</td><td class="col-xs-3">';
                                // item+='<select name="row[user]['+v['id']+'][role]"> <option value="1">业务经理</option><option value="2">业务员</option></select>';
                                // item+='</td><td class="col-xs-3">';
                                //  item+='<span class="btn btn-primary btn-embossed" style="background-color:#f75444" οnclick="delUser('+v['id']+')">删除</span>';
                                item += '</td></tr>';
                            })
                        } else {
                            $.each(ret, function (k, v) {

                                item += "<tr id='del_" + v['sku']['id'] + "'>" +
                                    "<td class='col-xs-3' ><input type='hidden' name='row[goods][" + k + "][title]' value='" + v['goods']['title'] + "'><input type='hidden' name='row[goods][" + k + "][sku_id]' value='" + v['sku']['id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][goods_id]' value='" + v['goods']['id'] + "'> " +
                                    "<input type='hidden' name='row[goods][" + k + "][image]' value='" + v['goods']['image'] + "'> ";
                                item += v['goods']['title'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][difference]' value='" + v['sku']['difference'] + "'>";
                                item += v['sku']['difference'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[goods][" + k + "][price]' value='" + v['sku']['price'] + "'>";
                                item += v['sku']['price'];
                                item += '</td><td class="col-xs-3"><input type="number" class="ipt-num" name="row[goods][' + k + '][nums]" value=""></td>' +
                                    '<td class="col-xs-3">';
                                // item+=v['mobile'];
                                // item+='</td><td class="col-xs-3">';
                                // item+='<select name="row[user]['+v['id']+'][role]"> <option value="1">业务经理</option><option value="2">业务员</option></select>';
                                // item+='</td><td class="col-xs-3">';
                                //  item+='<span class="btn btn-primary btn-embossed" style="background-color:#f75444" οnclick="delUser('+v['id']+')">删除</span>';
                                item += '</td></tr>';
                            })
                        }
                        $('#table').html(item)
                        if (type == 3) {
                            $('.all-num-box').show()
                        }

                    }
                }, function (ret) {
                    Toastr.error(ret.msg);
                });


            });
            $('.all-num').on('input', function () {

                $('.ipt-num').val($(this).val())
            })
        },
        send_goods: function () {
            $("#showTable").hide()
            Controller.api.bindevent();

            $(document).on("click", "#c-goods", function () {
                //后续操作
                var name = $("#c-name").val();
                var type = $("#type").html();
                Fast.api.ajax({
                    url: 'item/item/get_goods',
                    dataType: 'json',
                    data: { name: name },
                    cache: false
                }, function (ret) {
                    if (ret.length > 0) {
                        $("#showTable").show()
                        var head = '<tr>\n' +
                            '                                        <th scope="col">已选服务（' + ret.length + '）</th>\n' +
                            '                                        <th scope="col">规格</th>\n' +
                            '                                        <th scope="col">售价</th>\n' +
                            '                                        <th scope="col">可用次数</th>\n' +
                            // '                                        <th scope="col">操作</th>\n' +
                            '                                </tr>'
                        $("#head").html(head);
                        var item = '';
                        if (type == 2) {
                            $.each(ret, function (k, v) {

                                item += "<tr id='del_" + v['sku']['id'] + "'>" +
                                    "<td class='col-xs-3' ><input type='hidden' name='row[send_goods][" + k + "][title]' value='" + v['goods']['title'] + "'><input type='hidden' name='row[send_goods][" + k + "][sku_id]' value='" + v['sku']['id'] + "'> " +
                                    "<input type='hidden' name='row[send_goods][" + k + "][goods_id]' value='" + v['goods']['id'] + "'> " +
                                    "<input type='hidden' name='row[send_goods][" + k + "][image]' value='" + v['goods']['image'] + "'> ";
                                item += v['goods']['title'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[send_goods][" + k + "][difference]' value='" + v['sku']['difference'] + "'>";
                                item += v['sku']['difference'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[send_goods][" + k + "][price]' value='" + v['sku']['price'] + "'>";
                                item += v['sku']['price'];
                                item += '</td><td class="col-xs-3"><input type="text" name="row[send_goods][' + k + '][nums]" value="无限次" readonly></td>' +
                                    '<td class="col-xs-3">';

                                item += '</td></tr>';
                            })
                        } else {
                            $.each(ret, function (k, v) {

                                item += "<tr id='del_" + v['sku']['id'] + "'>" +
                                    "<td class='col-xs-3' ><input type='hidden' name='row[send_goods][" + k + "][title]' value='" + v['goods']['title'] + "'><input type='hidden' name='row[send_goods][" + k + "][sku_id]' value='" + v['sku']['id'] + "'> " +
                                    "<input type='hidden' name='row[send_goods][" + k + "][goods_id]' value='" + v['goods']['id'] + "'> " +
                                    "<input type='hidden' name='row[send_goods][" + k + "][image]' value='" + v['goods']['image'] + "'> ";
                                item += v['goods']['title'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[send_goods][" + k + "][difference]' value='" + v['sku']['difference'] + "'>";
                                item += v['sku']['difference'];
                                item += "<td class='col-xs-3'> <input type='hidden' name='row[send_goods][" + k + "][price]' value='" + v['sku']['price'] + "'>";
                                item += v['sku']['price'];
                                item += '</td><td class="col-xs-3"><input type="number" name="row[send_goods][' + k + '][nums]" value=""></td>' +
                                    '<td class="col-xs-3">';
                                // item+=v['mobile'];
                                // item+='</td><td class="col-xs-3">';
                                // item+='<select name="row[user]['+v['id']+'][role]"> <option value="1">业务经理</option><option value="2">业务员</option></select>';
                                // item+='</td><td class="col-xs-3">';
                                //  item+='<span class="btn btn-primary btn-embossed" style="background-color:#f75444" οnclick="delUser('+v['id']+')">删除</span>';
                                item += '</td></tr>';
                            })
                        }


                        $('#table').html(item)
                    }
                }, function (ret) {
                    Toastr.error(ret.msg);
                });


            });
        },
        resubmit: function () {
            var goods_id = Config.goods_id;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'item/item/resubmit?ids=' + goods_id +"&"+ location.search,
                    // table: 'wanlshop_shop',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                // sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'code', title: __('店铺编号'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });

            $("button[type='submit']").css("background-color","red");
            $("button[type='submit']").css("border-color","red");

            //保存设置
            $(document).on("click", ".choose-shop", function () {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    layer.msg("请选择要铺设的店铺！");
                }
                Fast.api.ajax({
                    url: 'item/item/savegoodsshop',
                    type: 'post',
                    loading: false,
                    data: {
                        ids: ids,
                        goods_id: goods_id
                    }
                }, function (data, ret) {
                    if (ret.code == 1) {
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">铺设成功</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }else{
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">操作失败，请售后重试！</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }
                    return false;
                });
            });
            
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        batch: function () {
            var goods_id = Config.goods_id;
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'item/item/batch?ids=' + goods_id +"&"+ location.search,
                    // table: 'wanlshop_shop',
                }
            });

            var table = $("#table");

            $(".btn-add").data("area", ["100%", "100%"]);

            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                // sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible:false, operate: false},
                        {field: 'code', title: __('店铺编号'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'type', title: __('商家分类'), searchList: {"0":__('直营店'),"1":__('加盟店'),"2":__('社区单店')}, operate: false,formatter: Table.api.formatter.normal},
                        {field: 'shopname', title: __('商家名称'), operate: 'LIKE'},
                        {field: 'person', title: __('联系人'), operate: 'LIKE', operate: false},
                        {field: 'telephone', title: __('联系方式'), operate: 'LIKE', operate: false},
                        {field: 'city', title: __('所属地区'), operate: 'LIKE', operate: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('营业中'),"hidden":__('下线')}, formatter: Table.api.formatter.status, operate: false}
                    ]
                ]
            });

            $("button[type='submit']").css("background-color","red");
            $("button[type='submit']").css("border-color","red");

            //保存设置
            $(document).on("click", ".choose-shop", function () {
                var ids = Table.api.selectedids(table);
                if (ids.length == 0) {
                    layer.msg("请选择要设置的店铺！");
                }
                Fast.api.ajax({
                    url: 'item/item/batchdelistingshop',
                    type: 'post',
                    loading: false,
                    data: {
                        ids: ids,
                        goods_id: goods_id
                    }
                }, function (data, ret) {
                    if (ret.code == 1) {
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">下架成功</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }else{
                        Layer.open({
                            title:'提示',
                            type: 1, 
                            area: ['280px', '180px'],
                            content: '<p style="padding: 15px;font-size: 16px;color: #ff0000;">操作失败，请售后重试！</p>',
                            btn: ['确定'], // 弹窗按钮
                            btnAlign:"c",
                            yes: function(index, layero){
                                // 点击确定按钮后的回调函数
                                // index是弹窗的索引，layero是弹窗的DOM对象
                                // Layer.close(index);
                                parent.Layer.closeAll();
                                parent.$("a.btn-refresh").trigger("click");
                            }
                        });
                    }
                    return false;
                });
            });
            
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        topgoods: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'item/item/topgoods' + location.search,
                    add_url: 'item/item/add',
                   // edit_url: 'item/item/edit',
                   // del_url: 'item/item/del',
                    multi_url: 'item/item/multi',
                    resubmit_url: 'item/item/resubmit',
                    dragsort_url: "",
                    table: 'item',
                }
            });

            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);

            $(document).on("click", ".goods-shop-type-item", function () {
                $(".active-type").removeClass('active-type');
                $(this).addClass('active-type');
                window.location =  $(this).data('url');
            });
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                    $(".btn-editone").data("area", ["100%", "100%"]);
             });

            table.on('post-common-search.bs.table', function (event, table) {
                $('ul.nav-tabs li a[data-value="normal"]').trigger('click');
                $(".form-commonsearch select[name=status]").val("normal");
            });
            
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                Search: true,
                commonSearch: true,
                searchFormVisible: true,
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), operate: false },
                        // {field: 'shop_id', title: __('Shop_id')},
                        //     {field: 'code', title: __('Code'), operate: 'LIKE'},
                        { field: 'name', title: __('Name'), operate: 'LIKE' },
                        { field: 'type', title: __('Type'), searchList: { "1": __('Type 1'), "2": __('Type 2'), "3": __('Type 3'), "4": __('Type 4'), "5": __('Type 5') }, formatter: Table.api.formatter.normal },
                        { field: 'flag.name', title: __('Category_id') },


                        // {field: 'consumption', title: __('Consumption'), searchList: {"1":__('Consumption 1'),"2":__('Consumption 2'),"3":__('Consumption 3'),"4":__('Consumption 4')}, formatter: Table.api.formatter.normal},
                        { field: 'price', title: __('Price'), operate: false },
                        //{field: 'specs', title: __('Specs'), searchList: {"1":__('Specs 1')}, formatter: Table.api.formatter.normal},
                        //{field: 'image', title: __('Image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        //                 {field: 'gift', title: __('Gift'), operate:'BETWEEN'},
                        //{field: 'spent', title: __('Spent')},
                        //              {field: 'total', title: __('Total')},
                        { field: 'validity', title: __('Validity'), operate: false, searchList: { "0": __('Validity 0'), "1": __('Validity 1'), "3": __('Validity 3') }, formatter: Table.api.formatter.normal },
                        // {field: 'validitytime', title: __('Validitytime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'shop_ids', title: __('Shop_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'stock', title: __('Stock'), searchList: {"0":__('Stock 0'),"2":__('Stock 2'),"3":__('Stock 3')}, formatter: Table.api.formatter.normal},
                        { field: 'activity', title: __('Activity'), operate: false, searchList: { "0": __('Activity 0'), "1": __('Activity 1') }, formatter: Table.api.formatter.normal },
                        //  {field: 'distribution', title: __('Distribution'), searchList: {"0":__('Distribution 0'),"1":__('Distribution 1')}, formatter: Table.api.formatter.normal},
                        //   {field: 'flag', title: __('Flag'), searchList: {"type":__('Flag type'),"name":__('Flag name'),"rec":__('Flag rec')}, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                        //  {field: 'activity_type', title: __('Activity_type'), searchList: {"goods":__('Activity_type goods'),"groups":__('Activity_type groups'),"seckill":__('Activity_type seckill'),"bargain":__('Activity_type bargain')}, formatter: Table.api.formatter.normal},
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        //{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        { field: 'status', title: __('Status'), searchList: { "normal": __('Normal'), "hidden": __('Hidden') }, formatter: Table.api.formatter.status },
                        // { field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons :[
                                {
                                    name: 'detail',
                                    text: '商品详情',
                                    title: '商品详情',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: "item/item/detail",
                                },
                                {
                                    name: 'resubmittoshop',
                                    text: '添加到本店',
                                    title: '添加到本店',
                                    icon: '',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    url: "item/item/resubmittoshop",
                                    refresh: true,
                                    hidden:function(row){
                                        if(row.already_copy == 1){
                                            return true;
                                        }else{
                                            return false;
                                        }
                                    },
                                },
                            ],
                            callback: function (data) {
                                table.bootstrapTable('refresh', {});
                                return false;
                            },
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        detail: function() {
            $("input").attr('disabled',true);
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
